/*
 * Created by Jaren at 2021/10/28 17:49
 */
import 'package:ble_plugin_example/base/base.dart';
import 'package:ble_plugin_example/search/search_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';

class SearchPage extends BaseView<SearchBLEController> {
  _buildListView(SearchBLEController controller) {
    return ListView.builder(
      itemCount: controller.devices.length,
      itemBuilder: (context, index) {
        final item = controller.devices[index];
        return ListTile(
          onTap: () {
            controller.connect(device: item);
            controller.showConnectingDialog();
          },
          title: Text(item.name),
          subtitle: Text(item.id.id),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    Get.put(SearchBLEController());
    return Scaffold(
        appBar: AppBar(
          title: Text("Scan Device"),
          actions: [
            Obx(() => TextButton(
                  child: Text(
                    controller.searching.value ? 'STOP' : 'SCAN',
                    style: TextStyle(color: Color.fromARGB(0xFF, 0xFF, 0xFF, 0xFF)),
                  ),
                  style: TextButton.styleFrom(
                    textStyle: const TextStyle(fontSize: 20),
                  ),
                  onPressed: controller.btState.value == BluetoothState.on
                      ? () {
                          if (controller.searching.value)
                            controller.stopScanning();
                          else
                            controller.scan();
                        }
                      : null,
                ))
          ],
        ),
        body: Column(
          children: [
            Expanded(
              child: Obx(
                () => RefreshIndicator(
                  onRefresh: () async {
                    controller.devices.clear();
                    controller.scan();
                  },
                  child: _buildListView(controller),
                ),
              ),
            ),
          ],
        ));
  }
}
